package com.example.myapplication.webview;

import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.os.Process;
import android.os.RemoteException;
import android.text.TextUtils;

import androidx.annotation.NonNull;

import com.example.webview.IMainProcessToWebViewProcessInterface;
import com.example.webview.webviewprocess.command.Command;
import com.google.auto.service.AutoService;
import com.google.gson.Gson;

import java.util.HashMap;
import java.util.Map;


/**
 * Created by ymz0427 on 2021/10/7
 */
@AutoService({Command.class})
public class LoginCommand implements Command {

    private final static int LOGIN_WHAT = 10;

    private final Handler handler = new android.os.Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(@NonNull Message msg) {
            if (msg.what == LOGIN_WHAT) {
                if (!TextUtils.isEmpty(params) && callback != null) {
                    Map<?, ?> map = new Gson().fromJson(params, Map.class);
                    if (map != null) {
                        String callbackname = String.valueOf(map.get("callbackname"));
                        Map<String, String> response = new HashMap<>();
                        response.put("username", "User" + System.currentTimeMillis());
                        try {
                            callback.onResponse(callbackname, new Gson().toJson(response));
                        } catch (RemoteException e) {
                            e.printStackTrace();
                        }
                    }
                }
                return true;
            }
            return false;
        }
    });

    private IMainProcessToWebViewProcessInterface callback;
    private String params;


    @Override
    public String getName() {
        return "login";
    }

    @Override
    public void execute(String params) {

    }

    @Override
    public void execute(String params, IMainProcessToWebViewProcessInterface callback) {
        System.out.println("执行进程：" + Process.myPid());
        this.callback = callback;
        this.params = params;
        handler.sendEmptyMessageDelayed(LOGIN_WHAT, 1000);
    }
}
